import os

import requests

def download_file(url):
    save_path = "temp/data/"
    os.makedirs(save_path, exist_ok=True)
    # 文件名
    file_name = save_path + url.split('/')[-1]
    try:
        # 发起GET请求，stream=True表示不立即下载内容
        with requests.get(url, stream=True, timeout=30) as response:
            response.raise_for_status()  # 检查HTTP错误
            # 获取文件总大小（可选）
            total_size = int(response.headers.get('content-length', 0))
            print("文件大小：", total_size)
            # 分块下载
            with open(file_name, 'wb') as file:
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:  # 过滤保持连接的chunk
                        file.write(chunk)
        print(f"文件下载成功，保存路径：{file_name}")
        return file_name
    except PermissionError:
        print(f"错误：无权限写入路径 {file_name}")
    except requests.exceptions.RequestException as e:
        print(f"下载失败，请求错误: {str(e)}")
    except IOError as e:
        print(f"文件写入失败: {str(e)}")

def upload_file(file_path):
    upload_url = "http://localhost:8000/common/file"
    try:
        # 确保文件存在
        if not os.path.isfile(file_path):
            raise FileNotFoundError(f"文件不存在：{file_path}")

        # 构造文件参数（关键修复：移除手动Content-Type）
        files = {
            'file': (os.path.basename(file_path),  # 使用纯文件名（不含路径）
                     open(file_path, 'rb'),  # 二进制模式打开
                     'application/octet-stream')  # 通用类型（或指定具体MIME类型）
        }

        # 发送POST请求
        response = requests.post(
            url=upload_url,
            files=files,
            # headers={'Content-Type': 'multipart/form-data'}  # 通常由requests自动设置，但显式声明更安全
        )
        # 检查响应状态
        response.raise_for_status()
        # url转换成str "\"http://localhost:8000/file/2025/5/14/6824653af81f2a2765a68249.png\""
        url = response.json()['data']['url']
        print(type(url))
        return url

    except FileNotFoundError:
        print(f"错误：文件未找到 {file_path}")
    except requests.exceptions.RequestException as e:
        print(f"请求异常：{str(e)}")
        if hasattr(e, 'response'):
            print(f"服务器返回：{e.response.text}")
    except Exception as e:
        print(f"未知错误：{str(e)}")

if __name__ == '__main__':
    url = "http://localhost:8000/file/2025/5/13/68221efa94aba3be2ecd6f48.png"
    download_file(url)

    # result_path = '../temp/result/'
    # file_path = result_path + "Time--Domain--Waveform--2025_05_09_214958—-Test_2024_08_21_095324.png"
    # print(upload_file(file_path))